#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
User Plane Signaling Analysis Tool - Main Program
用户面信令分析工具 - 主程序

功能：
1. 自动检测data文件夹中的pcap文件
2. 调用pcap解析脚本生成JSON文件
3. 调用JSON分析脚本生成分析结果
4. 调用网页生成脚本创建最终报告
5. 提供完整的分析流程

作者：AI Assistant
版本：1.0
日期：2025-08-15
"""

import os
import sys
import json
import time
import subprocess
from pathlib import Path
from datetime import datetime

class SignalingAnalysisTool:
    def __init__(self):
        self.project_root = Path(__file__).parent
        self.data_dir = self.project_root / "data"
        self.json_dir = self.project_root / "json"
        self.scripts_dir = self.project_root / "scripts"
        self.styles_dir = self.project_root / "styles"
        self.docs_dir = self.project_root / "docs"
        
        # 确保目录存在
        self._ensure_directories()
        
        # 脚本路径
        self.pcap_parser = self.scripts_dir / "pcap_parser.py"
        self.json_analyzer = self.scripts_dir / "json_analyzer.py"
        self.web_generator = self.scripts_dir / "web_generator.py"
        
        print("User Plane Signaling Analysis Tool Started")
        print(f"Project Root: {self.project_root}")
        print(f"Data Directory: {self.data_dir}")
        print(f"JSON Directory: {self.json_dir}")
        print(f"Scripts Directory: {self.scripts_dir}")
        print(f"Styles Directory: {self.styles_dir}")
        print(f"Docs Directory: {self.docs_dir}")
        print("-" * 60)

    def _ensure_directories(self):
        """确保所有必要的目录都存在"""
        for directory in [self.data_dir, self.json_dir, self.scripts_dir, self.styles_dir, self.docs_dir]:
            directory.mkdir(exist_ok=True)

    def scan_pcap_files(self):
        """扫描data目录中的pcap文件"""
        pcap_files = list(self.data_dir.glob("*.pcap"))
        if not pcap_files:
            print("No .pcap files found in data directory")
            print("Please place pcap files in the data directory")
            return []
        
        print(f"Found {len(pcap_files)} pcap files:")
        for pcap_file in pcap_files:
            print(f"  {pcap_file.name}")
        return pcap_files

    def check_scripts(self):
        """检查必要的脚本文件是否存在"""
        required_scripts = [self.pcap_parser, self.json_analyzer, self.web_generator]
        missing_scripts = []
        
        for script in required_scripts:
            if not script.exists():
                missing_scripts.append(script.name)
        
        if missing_scripts:
            print(f"Missing required script files: {', '.join(missing_scripts)}")
            print("Please ensure all script files are in the scripts directory")
            return False
        
        print("All required script files check passed")
        return True

    def run_pcap_parser(self, pcap_file):
        """运行pcap解析脚本"""
        print(f"\nStarting pcap file parsing: {pcap_file.name}")
        
        try:
            # 调用pcap解析脚本
            result = subprocess.run([
                sys.executable, str(self.pcap_parser),
                str(pcap_file),
                str(self.json_dir)
            ], capture_output=True, text=True, cwd=self.project_root)
            
            if result.returncode == 0:
                print(f"Pcap file parsing successful: {pcap_file.name}")
                return True
            else:
                print(f"Pcap file parsing failed: {pcap_file.name}")
                print(f"Error: {result.stderr}")
                return False
                
        except Exception as e:
            print(f"Error running pcap parser script: {e}")
            return False

    def run_json_analyzer(self, json_file):
        """运行JSON分析脚本"""
        print(f"\nStarting JSON file analysis: {json_file.name}")
        
        try:
            # 调用JSON分析脚本
            result = subprocess.run([
                sys.executable, str(self.json_analyzer),
                str(json_file),
                str(self.docs_dir)
            ], capture_output=True, text=True, cwd=self.project_root)
            
            if result.returncode == 0:
                print(f"JSON file analysis successful: {json_file.name}")
                return True
            else:
                print(f"JSON file analysis failed: {json_file.name}")
                print(f"Error: {result.stderr}")
                return False
                
        except Exception as e:
            print(f"Error running JSON analyzer script: {e}")
            return False

    def run_web_generator(self, analysis_data):
        """运行网页生成脚本"""
        print(f"\nStarting analysis webpage generation")
        
        try:
            # 调用网页生成脚本
            result = subprocess.run([
                sys.executable, str(self.web_generator),
                str(self.docs_dir),
                str(self.styles_dir),
                str(self.project_root)
            ], capture_output=True, text=True, cwd=self.project_root)
            
            if result.returncode == 0:
                print("Analysis webpage generation successful")
                return True
            else:
                print("Analysis webpage generation failed")
                print(f"Error: {result.stderr}")
                return False
                
        except Exception as e:
            print(f"Error running web generator script: {e}")
            return False

    def generate_summary_report(self, pcap_files, success_count):
        """生成总结报告"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        summary = f"""
# User Plane Signaling Analysis Tool - Analysis Report

## Analysis Time
{timestamp}

## Analysis Results
- Total pcap files: {len(pcap_files)}
- Successfully analyzed: {success_count}
- Failed: {len(pcap_files) - success_count}

## Generated Files
- JSON files: {self.json_dir}
- Analysis documents: {self.docs_dir}
- Analysis webpage: {self.project_root / "sidebar_analysis.html"}

## Usage Instructions
1. Place pcap files in the data directory
2. Run the main program: python main.py
3. View the generated analysis results

## Notes
- Ensure all dependencies are installed
- Check script file permissions
- Review error logs for troubleshooting
"""
        
        summary_file = self.project_root / "analysis_summary.md"
        with open(summary_file, 'w', encoding='utf-8') as f:
            f.write(summary)
        
        print(f"\nSummary report generated: {summary_file}")

    def run_analysis(self):
        """运行完整的分析流程"""
        print("\n" + "="*60)
        print("Starting User Plane Signaling Analysis Process")
        print("="*60)
        
        # 1. 检查脚本文件
        if not self.check_scripts():
            return False
        
        # 2. 扫描pcap文件
        pcap_files = self.scan_pcap_files()
        if not pcap_files:
            return False
        
        # 3. 执行分析流程
        success_count = 0
        for pcap_file in pcap_files:
            print(f"\n{'='*40}")
            print(f"Processing file: {pcap_file.name}")
            print(f"{'='*40}")
            
            # 解析pcap文件
            if self.run_pcap_parser(pcap_file):
                # 查找生成的JSON文件
                json_file = self.json_dir / f"{pcap_file.stem}.json"
                if json_file.exists():
                    # 分析JSON文件
                    if self.run_json_analyzer(json_file):
                        success_count += 1
                    else:
                        print(f"JSON analysis failed, skipping subsequent steps")
                else:
                    print(f"Corresponding JSON file not found: {json_file}")
            else:
                print(f"Pcap parsing failed, skipping subsequent steps")
        
        # 4. 生成网页报告
        if success_count > 0:
            print(f"\n{'='*40}")
            print("Generating final analysis webpage")
            print(f"{'='*40}")
            self.run_web_generator({"success_count": success_count})
        
        # 5. 生成总结报告
        self.generate_summary_report(pcap_files, success_count)
        
        print(f"\n{'='*60}")
        print(f"Analysis process completed!")
        print(f"Successfully processed: {success_count}/{len(pcap_files)} files")
        print(f"Results location: {self.project_root}")
        print(f"{'='*60}")
        
        return success_count > 0

def main():
    """主函数"""
    try:
        tool = SignalingAnalysisTool()
        success = tool.run_analysis()
        
        if success:
            print("\nAll analysis tasks completed! Please check the generated result files.")
        else:
            print("\nErrors occurred during analysis, please check the log information.")
            
    except KeyboardInterrupt:
        print("\n\nUser interrupted operation")
    except Exception as e:
        print(f"\nProgram runtime error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main() 